﻿using System;
using System.Collections.Generic;
using System.Text;
using Roovent.Network;
using System.Threading;
using System.Diagnostics;

namespace UnionnetClient.Model
{
	public class AppEnvironment
	{
		static public event EventHandler StateChanged;

		static public string AppDataFolder
		{
			get { return appDataFolder; }
			set { appDataFolder = value; }
		}

		static public AppSettings Settings
		{
			get { return AppSettings.Instance; }
		}

		static public StateBase CurrentState
		{
			get { return stateMachine.CurrentState; }
		}

		static public void Run(IStateFactory stateFactory, DoSomething errorHandle)
		{
			stateMachine = new StateMachine(stateFactory);
			stateMachine.StateChanged += delegate(object sender, EventArgs e) { OnStateChanged(e); };

			if (NetworkTool.GetIsConnectedToInternet())
			{
				stateMachine.SetState(stateMachine.UnknownLoginedS);
				((LoginedState)AppEnvironment.CurrentState).StartTestNetwork();
				return;
			}
			
			if (!AppEnvironment.Settings.IsCompleted)
			{
				stateMachine.SetState(stateMachine.UnconfigS);
				return;
			}

			Debug.WriteLine("Set to UnloginState.");
			stateMachine.SetState(stateMachine.UnloginS);

			if ((bool)AppEnvironment.Settings[SettingsProperty.AutoLogin])
			{
				Thread autoLoginThread = new Thread(AutoLogin);
				autoLoginThread.Name = "Autologin Thread";
				autoLoginThread.Start();
				
				object[] parameters = new object[]{autoLoginThread, errorHandle};
				timer = new Timer(KillAutoLogin, parameters, 60000, 0);
			}
		}

		static private string appDataFolder;
		static private Timer timer;
		static StateMachine stateMachine;

		static private void AutoLogin()
		{
			while (!NetworkTool.GetIsNetworkAdapterAvailable())
			{
				Thread.Sleep(5000);
			}

			if (!NetworkTool.GetIsConnectedToInternet())
			{
				CurrentState.Login();
			}
			else
			{
				stateMachine.SetState(stateMachine.UnknownLoginedS);
				((LoginedState)AppEnvironment.CurrentState).StartTestNetwork();
			}
		}

		static private void KillAutoLogin(object parameters)
		{
			object[] p = (object[])parameters;
			Thread th = (Thread)p[0];
			DoSomething ds = (DoSomething)p[1];
			if (th.IsAlive)
			{
				th.Abort();
				if (ds != null)
				{
					ds();
				}
			}
		}

		static private void OnStateChanged(EventArgs e)
		{
			if (StateChanged != null)
			{
				StateChanged(null, e);
			}
		}
	}
}
